<?php

namespace app\supplier\model\plus\assemble;

use app\common\enum\order\OrderSourceEnum;
use app\common\model\plus\assemble\Active as ActiveModel;
use app\common\model\plus\assemble\Bill as BillModel;
use app\common\model\plus\assemble\Product as AssembleProductModel;
use app\common\model\plus\assemble\AssembleSku as AssembleSkuModel;
use app\proxy\model\auth\User as ProxyUser;
use app\shop\model\order\Order as OrderModel;
use app\supplier\model\supplier\Supplier;

/**
 *
 */
class Active extends ActiveModel
{
    public function getList($data, $shop_supplier_id)
    {
        // 获取数据列表

        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        // 获取数据列表
        $model = $this;
        if (isset($data["title"]) && !empty($data["title"])) {
            $data["title"] = trim($data["title"]);
            $model = $model->where("title", 'like','%'.$data["title"].'%');
        }
        if (isset($data["status"]) && $data["status"] !== "") {
            switch ($data["status"]) {
                case 0:
                    $model = $model->where(function ($query) {
                        $query->where("start_time", ">", time());
                    });
                    break;
                case 1:
                    $model = $model->where("status", 1)->where("start_time", "<", time())->where("end_time", ">", time());
                    break;
                case 2:
                    $model = $model->where("status", 1)->where("end_time", "<", time());
                    break;
            }
        }
        $list = $model->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->where('status', '=', 1)
            ->where('is_delete', '=', 0)
            ->where(function ($query) use ($supplier) {
                $query->where("shop_supplier_id", $supplier["shop_supplier_id"]);
                    // ->whereOr("proxy_id", $supplier["proxy_id"])->where("proxy_id", 0);
            })
            ->paginate($data);
        foreach ($list as $active) {
            $active["can_edit"] = $active["shop_supplier_id"] == $shop_supplier_id ? 1 : 0;
            //商品数
            $product_model = new AssembleProductModel();
            $active['product_num'] = $product_model
                ->where('assemble_activity_id', '=', $active['assemble_activity_id'])
                ->where('status', '=', 10)
                ->count();
            $active['product_audit_num'] = $product_model
                ->where('assemble_activity_id', '=', $active['assemble_activity_id'])
                ->where('status', '=', 0)
                ->count();
            //订单数
            $active['total_sales'] = $product_model->where('assemble_activity_id', '=', $active['assemble_activity_id'])->sum('total_sales');
        }

        return $list;
    }

    public function add($shop_supplier_id, $data)
    {
        $this->startTrans();
        try {
            //添加商品
            $stock = array_sum(array_column($data['product']['spec_list'], 'assemble_stock'));
            $arr = [
                'product_id' => $data['product_id'],
                'assemble_activity_id' => $data['assemble_activity_id'],
                'app_id' => self::$app_id,
                'stock' => $stock,
                'limit_num' => $data['limit_num'],
                'assemble_num' => $data['assemble_num'],
                'teamwork_type' => $data['teamwork_type'],
                'assemble_num' => $data['assemble_num'],
                'order_number' => $data['order_number']??0,
                'product_number' => $data['product_number']??0,
                'shop_supplier_id' => $shop_supplier_id
            ];

            $model = new AssembleProductModel();
            $model->save($arr);
            //商品规格
            $sku_model = new AssembleSkuModel();
            $sku_data = [];
            foreach ($data['product']['spec_list'] as $sku) {
                $sku_data[] = [
                    'assemble_product_id' => $model['assemble_product_id'],
                    'product_id' => $data['product_id'],
                    'product_sku_id' => $sku['product_sku_id'],
                    'assemble_price' => $sku['assemble_price'],
                    'product_price' => $sku['product_price'],
                    'assemble_stock' => $sku['assemble_stock'],
                    'product_attr' => isset($sku['product_attr']) ? $sku['product_attr'] : '',
                    'assemble_activity_id' => $data['assemble_activity_id'],
                    'app_id' => self::$app_id,
                ];
            }
            $sku_model->saveAll($sku_data);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public function addActive($data, $shop_supplier_id)
    {
        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        $this->startTrans();
        try {

            $arr = $this->setData($data, $supplier);

            $this->save($arr);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    /**
     * 修改
     */
    public function editActive($data, $shop_supplier_id)
    {
        $supplier = (new Supplier())->find($shop_supplier_id);
        if (!$supplier || $supplier["is_recycle"] == 1 || $supplier["is_audit"] != 1) {
            $this->error = "商户不存在或异常";
            return false;
        }
        $this->startTrans();
        try {
            if ($shop_supplier_id != $this["shop_supplier_id"]) {
                $this->error = "你无权修改此活动";
                $this->rollback();
                return false;
            }
            $arr = $this->setData($data, $supplier);
            $this->save($arr);
            // 事务提交
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->error = $e->getMessage();
            $this->rollback();
            return false;
        }
    }

    public function del()
    {
        //如果有正在拼团的商品
        $count = (new BillModel())->where('status', '=', 10)
            ->where('assemble_activity_id', '=', $this['assemble_activity_id'])
            ->count();
        if ($count > 0) {
            $this->error = '该活动下有正在拼团的订单';
            return false;
        }
        // 如果有未付款订单不能删除
        $count = (new OrderModel())->where('pay_status', '=', 10)
            ->where('order_source', '=', OrderSourceEnum::ASSEMBLE)
            ->where('activity_id', '=', $this['assemble_activity_id'])
            ->where('is_delete', '=', 0)
            ->count();
        if ($count > 0) {
            $this->error = '该活动下有未付款的订单';
            return false;
        }
        return $this->save([
            'is_delete' => 1
        ]);
    }

    /**
     * 验证并组装数据
     * @param $data array  添加/新增数据
     * @return array
     */
    private function setData($data, $supplier)
    {
        $shAuth = Supplier::checkauth($supplier['shop_supplier_id'],'assemble');
        $data['active_time'][0] = substr($data['active_time'][0], 0, 16);
        $data['active_time'][1] = substr($data['active_time'][1], 0, 16);
        $arr = [
            'shop_supplier_id' => $supplier['shop_supplier_id'],
            'image_id' => $data['image_id'],
            'imgUrl' => $data['image_id'],
            'title' => $data['title'],
            'assemble_title' => $data['assemble_title']??'',
            'assemble_exp' => $data['assemble_exp']??'',
            'assemble_title_bgc' => $data['assemble_title_bgc']??'',
            'assemble_title_img' => $data['assemble_title_img']??'',
            'start_time' => strtotime($data['active_time'][0] . ':00'),
            'end_time' => strtotime($data['active_time'][1] . ':59'),
            'join_end_time' => strtotime($data['join_end_time']),
            'app_id' => self::$app_id,
            'together_time' => $data['together_time'],
            'sort' => $data['sort'],
            'status' => $data['status'],
            'fail_type' => $data['fail_type'],
            'is_single' => $data['is_single'],
            'supplier_range' => 2,
            'province_id' => $supplier["province_id"] ?? 0,
            'city_id' => $supplier["city_id"] ?? 0,
            'county_id' => $supplier["county_id"] ?? 0,
            'proxy_id' => $supplier["proxy_id"] ?? 0,
            'is_audit' => $shAuth?1:0
        ];
        return $arr;
    }
}